﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Daneas.Utility.Universals
{
    #region Random
    /// <summary>
    /// 获取随机数 的摘要说明。
    /// </summary>
    public class RandomHelper
    {

        /// <summary>
        /// 从字符串里随机得到，规定个数的字符串.
        /// </summary>
        /// <param name="sourceChar">数据源1-9 a-z</param>
        /// <param name="CodeCount">长度</param>
        /// <returns></returns>
        public static string GetRandomCode(string sourceChar, int CodeCount)
        {
            //string allChar = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; 
            string[] allCharArray = sourceChar.Split(',');
            string RandomCode = "";
            int temp = -1;
            Random rand = new Random();
            for (int i = 0; i < CodeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
                }

                int t = rand.Next(allCharArray.Length - 1);

                while (temp == t)
                {
                    t = rand.Next(allCharArray.Length - 1);
                }

                temp = t;
                RandomCode += allCharArray[t];
            }
            return RandomCode;
        }

        /// <summary>
        /// 获取不重复的随机码
        /// </summary>
        /// <param name="sourceChar">源字符</param>
        /// <param name="CodeCount">长度</param>
        /// <returns></returns>
        public static string GetRandomCodeNorepeat(string sourceChar, int CodeCount)
        {
            string[] charArray = sourceChar.Split(',');
            string randomCode = "";

            Random rand = new Random();

            for (int i = 0; i < CodeCount; i++)
            {
                //位置
                int index = rand.Next(0, sourceChar.Length - 1);

                string target = sourceChar[index].ToString();

                if (randomCode.Contains(target))
                {
                    i = i - 1;
                    continue;
                }

                randomCode += target;
            }

            return randomCode;
        }
    }
    #endregion
}
